<template>
  <el-form label-width="100px">
    <el-form-item label="spu名称">
      <el-input
        v-model="SpuParams.spuName"
        placeholder="请输入spu名称"
      ></el-input>
    </el-form-item>
    <el-form-item label="spu品牌">
      <el-select v-model="SpuParams.tmId">
        <!--  index -->
        <el-option
          :value="item.id"
          :label="item.tmName"
          v-for="item in AllTradeMark"
          :key="item.id"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="spu名称">
      <el-input
        type="textarea"
        placeholder="请输入spu描述"
        v-model="SpuParams.description"
      ></el-input>
    </el-form-item>
    <el-form-item label="spu图片">
      <!-- v-model:file-list 展示默认图片 
                action:上传图片接口地址
                list-type:文件列表类型
                -->
      <el-upload
        v-model:file-list="imageList"
        action="/api/admin/product/fileUpload"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :before-upload="handlerUpload"
      >
        <el-icon>
          <Plus />
        </el-icon>
      </el-upload>

      <el-dialog v-model="dialogVisible">
        <img
          w-full
          :src="dialogImageUrl"
          alt="Preview Image"
          style="width: 100%; height: 100%"
        />
      </el-dialog>
    </el-form-item>
    <el-form-item label="spu销售属性">
      <!-- 展示销售属性下拉菜单 -->
      <el-select
        v-model="saleAttrIdAndValueName"
        :placeholder="
          unSelectSaleAttr.length
            ? `还未选择${unSelectSaleAttr.length}个`
            : '无'
        "
      >
        <!-- index -->
        <el-option
          :value="`${item.id}:${item.name}`"
          v-for="item in unSelectSaleAttr"
          :key="item.id"
          :label="item.name"
        ></el-option>
      </el-select>
      <el-button
        style="margin: 0px 10px"
        type="primary"
        icon="Plus"
        :disabled="saleAttrIdAndValueName ? false : true"
        @click="addSaleAttr"
      >
        添加属性
      </el-button>
      <!-- 展示销售属性和属性值 -->
      <el-table border style="margin: 10px 0px" :data="saleAttr">
        <el-table-column
          label="序号"
          type="index"
          algin="center"
          width="80px"
        ></el-table-column>
        <el-table-column
          label="销售属性名字"
          algin="center"
          width="120px"
          prop="saleAttrName"
        ></el-table-column>
        <el-table-column label="销售属性值" algin="center">
          <!-- row 当前spu已有的销售属性对象 -->
          <!-- $index -->
          <template #="{ row }">
            <el-tag
              style="margin: 0px 5px"
              @close="row.spuSaleAttrValueList.splice(index, 1)"
              v-for="(item, index) in row.spuSaleAttrValueList"
              :key="row.id"
              class="mx-1"
              closable
            >
              {{ item.saleAttrValueName }}
            </el-tag>
            <el-input
              @blur="toLook(row)"
              v-model="row.saleAttrValue"
              v-if="row.flag == true"
              placeholder="请输入属性值"
              size="small"
              style="width: 100px"
            ></el-input>
            <el-button
              v-else
              @click="toEdit(row)"
              type="primary"
              size="small"
              icon="Plus"
            ></el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" algin="center" width="120px">
          <!-- row, -->
          <template #="{ $index }">
            <el-button
              type="primary"
              size="small"
              icon="Delete"
              @click="saleAttr.splice($index, 1)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button
        type="primary"
        @click="save"
        :disabled="saleAttr.length > 0 ? false : true"
      >
        保存
      </el-button>
      <el-button type="primary" @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import type { SpuData } from '@/api/product/spu/type'
import {
  reqAllTradeMark,
  reqSpuImageList,
  reqSpuHasSaleAttr,
  reqAllSaleAttr,
  reqAddOrUpdateSpu,
} from '@/api/product/spu'

import type {
  SaleAttrValue,
  HasSaleAttr,
  SaleAttr,
  SpuImage,
  TradeMark,
  AllTradeMark,
  SpuHasImg,
  SaleAttrResponseData,
  HasSaleAttrResponseData,
} from '@/api/product/spu/type'
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
let $emit = defineEmits(['changeScene'])

//子组件点击取消按钮通知父组件切换场景为1 展示已有spu 属性
const cancel = () => {
  $emit('changeScene', { flag: 0, params: 'update' })
}

//存储已有spu数据
let AllTradeMark = ref<TradeMark[]>([])
//商品图片
let imageList = ref<SpuImage[]>([])
//已有的spu销售属性
let saleAttr = ref<SaleAttr[]>([])
//全部的销售属性
let allSaleAttr = ref<HasSaleAttr[]>([])
//存储已有的spu对象
let SpuParams = ref<SpuData>({
  spuName: '', //spu的名字
  description: '', //spu的描述
  category3Id: '', //3级分类id
  tmId: '', //品牌id
  spuSaleAttrList: [],
  spuImageList: [],
})
//存储预览图片的地址
let dialogImageUrl = ref<string>('')

//控制对话框的显示和隐藏
let dialogVisible = ref<boolean>(false)

//将来收集还未选择的销售属性的id与属性值的名字
let saleAttrIdAndValueName = ref<string>('')

//子组件方法
const initHasSpuData = async (spuForm: SpuData) => {
  //存储已有的spu对象，在模板中展示
  SpuParams.value = spuForm

  //spu为父组件传递的已有spu对象[不完整]
  //获取全部品牌数据
  let result: AllTradeMark = await reqAllTradeMark()
  //获取某一个品牌下全部售卖商品图片
  let result1: SpuHasImg = await reqSpuImageList(spuForm.id as number)
  //获取已有spu销售数组的数据
  let result2: SaleAttrResponseData = await reqSpuHasSaleAttr(
    spuForm.id as number,
  )
  //获取全部的spu销售属性
  let result3: HasSaleAttrResponseData = await reqAllSaleAttr()

  //存储全部品牌数据
  AllTradeMark.value = result.data
  //全部的spu对应商品图片
  imageList.value = result1.data.map((item) => {
    return {
      name: item.imgName,
      url: item.imgUrl,
    }
  })
  //存储已有spu销售属性
  saleAttr.value = result2.data
  //存储全部的销售属性
  allSaleAttr.value = result3.data
}

//展品墙点击预览按钮触发的钩子
const handlePictureCardPreview = (file: any) => {
  dialogImageUrl.value = file.url
  //对话框弹出
  dialogVisible.value = true
}

//照片墙删除文件的钩子
const handleRemove = () => {
  console.log(12)
}
//照片墙上传成功前的钩子
const handlerUpload = (file: any) => {
  if (
    file.type == 'image/png' ||
    file.type == 'image/jpeg' ||
    file.type == 'image/gif'
  ) {
    if (file.size / 1024 / 1024 < 3) {
      return true
    } else {
      ElMessage({
        type: 'error',
        message: '上传文件务必小于3M',
      })
      return false
    }
  } else {
    ElMessage({
      type: 'error',
      message: '上传文件务必是PNG|JPG|GIF',
    })
    return false
  }
}

//计算当前spu未有的销售属性
let unSelectSaleAttr = computed(() => {
  let unSelectAttr = allSaleAttr.value.filter((item) => {
    return saleAttr.value.every((item1) => {
      return item.name != item1.saleAttrName
    })
  })
  return unSelectAttr
})

//添加销售属性的方法
const addSaleAttr = () => {
  /**
    baseSaleAttrId: number,
    saleAttrName: string,
    spuSaleAttrValueList: SpuSaleAttrValueList
     */
  const [baseSaleAttrId, saleAttrName] = saleAttrIdAndValueName.value.split(':')
  //准备一个新的销售属性对象，将来带给服务器
  let newSaleAttr: SaleAttr = {
    baseSaleAttrId,
    saleAttrName,
    spuSaleAttrValueList: [],
  }
  //追加到数组当中
  saleAttr.value.push(newSaleAttr)
  //清空收集的数据
  saleAttrIdAndValueName.value = ''
}

//属性值按钮的点击事件
const toEdit = (row: SaleAttr) => {
  //点击按钮时 input组件显示 ->编辑模式
  row.flag = true
  row.saleAttrValue = ''
}

//表单元素失去焦点事件回调
const toLook = (row: SaleAttr) => {
  //收集属性id和属性名字
  const { baseSaleAttrId, saleAttrValue } = row
  //变为服务器需要的数据形式
  let newSaleAttrValue: SaleAttrValue = {
    baseSaleAttrId,
    saleAttrValueName: saleAttrValue as string,
  }

  //非法情况判断
  if ((saleAttrValue as string).trim() == '') {
    ElMessage({
      type: 'error',
      message: '属性值不能为空！',
    })
    return
  }
  //判断属性值是否在数组中存在
  let repeat = row.spuSaleAttrValueList.find((item) => {
    return item.saleAttrValueName == saleAttrValue
  })

  if (repeat) {
    ElMessage({
      type: 'error',
      message: '属性值重复！',
    })
    return
  }
  //追加新的属性值对象
  row.spuSaleAttrValueList.push(newSaleAttrValue)
  //切换为查看模式
  row.flag = false
}

//保存按钮的回调
const save = async () => {
  //整理参数
  //图片数据
  SpuParams.value.spuImageList = imageList.value.map((item: any) => {
    return {
      imgName: item.name,
      imgUrl: (item.resopnse && item.resopnse.data) || item.url,
    }
  })
  //整理销售属性数据
  SpuParams.value.spuSaleAttrList = saleAttr.value
  let result = await reqAddOrUpdateSpu(SpuParams.value)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: SpuParams.value.id ? '更新成功' : '添加成功',
    })
    //通知父组件切换场景
    $emit('changeScene', {
      flag: 0,
      params: SpuParams.value.id ? 'update' : 'add',
    })
  } else {
    ElMessage({
      type: 'error',
      message: SpuParams.value.id ? '更新失败' : '添加失败',
    })
  }
  //发请求：添加或修改
}

//添加一个新的spu 初始化请求放啊
const initAddSpu = async (c3Id: number | string) => {
  //清空数据
  Object.assign(SpuParams.value, {
    spuName: '', //spu的名字
    description: '', //spu的描述
    category3Id: '', //3级分类id
    tmId: '', //品牌id
    spuSaleAttrList: [],
    spuImageList: [],
  })
  //清空图片墙
  ;(imageList.value = []),
    //清空销售属性
    (saleAttr.value = []),
    //清空收集的数据
    (saleAttrIdAndValueName.value = ''),
    //存储3级分类id
    (SpuParams.value.category3Id = c3Id)
  //获取全部品牌数据
  let result: AllTradeMark = await reqAllTradeMark()
  //获取全部的spu销售属性
  let result1: HasSaleAttrResponseData = await reqAllSaleAttr()
  //存储数据
  AllTradeMark.value = result.data
  allSaleAttr.value = result1.data
}

defineExpose({ initHasSpuData, initAddSpu })
</script>

<style scoped></style>
